package vip.fuxk.blog.config;

import cn.zhxu.bs.IllegalParamException;
import cn.zhxu.bs.implement.PageSizeExtractor;
import cn.zhxu.bs.param.Paging;
import cn.zhxu.bs.util.MapBuilder;
import org.noear.solon.core.handle.Context;

import java.util.Map;

public class BsPageSizeExtractor extends PageSizeExtractor {


    public static final String BEAN_SEARCHR_SIZE ="BEAN_SEARCHR_SIZE";




    @Override
    public Paging extract(Map<String, Object> paraMap) throws IllegalParamException {
        Paging paging = doExtract(paraMap);
        int size = paging.getSize();
        if (size < 0 || size > getMaxAllowedSize()) {
            throw new IllegalParamException("Invalid page size: " + size + ", it must between 0 and " + getMaxAllowedSize());
        }
        long offset = paging.getOffset();
        if (offset < 0 || offset > getMaxAllowedOffset()) {
            throw new IllegalParamException("Invalid page offset: " + offset + ", it must between 0 and " + getMaxAllowedOffset());
        }
        Context.current().attrSet(BEAN_SEARCHR_SIZE,paging.getSize());
        return paging;
    }
    private Paging doExtract(Map<String, Object> paraMap) {
        Object value = paraMap.get(MapBuilder.PAGING);
        if (value instanceof MapBuilder.Page) {
            return toPaging((MapBuilder.Page) value);
        }
        if (value instanceof MapBuilder.Limit) {
            return toPaging((MapBuilder.Limit) value);
        }
        int size = toSize(paraMap.get(getSizeName()));
        return new Paging(size, toOffset(paraMap, size));
    }
}
